package lc;

import java.util.Arrays;

import org.junit.Test;

public class Ex221 {
    class Solution {
        public int maximalSquare(char[][] matrix) {
            int m = matrix.length;
            if (m == 0) return 0;
            int n = matrix[0].length, res = 0;

            int[][] left = new int[m][n], up = new int[m][n];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (matrix[i][j] == '1') {
                        left[i][j] = j > 0 ? left[i][j - 1] + 1 : 1;
                        up[i][j] = i > 0 ? up[i - 1][j] + 1 : 1;
                    }
                }
            }
            System.out.println(Arrays.deepToString(left));
            System.out.println(Arrays.deepToString(up));
            for (int i = m - 1; i >= 0; i--) {
                for (int j = n - 1; j >= 0; j--) {
                    if (matrix[i][j] == '1') {
                        int w = Math.min(left[i][j], up[i][j]);
                        for (int l = w; l >= res; l--) {
                            boolean flag = true;
                            for (int k = 1; k < l; k++) {
                                if (left[i - k][j] < l) {
                                    flag = false;
                                    break;
                                }
                            }
                            if (flag) {
                                res = Math.max(res, l);
                            }
                        }
                    }
                    if (j <= res) {
                        break;
                    }
                }
                if (i <= res) {
                    break;
                }
            }
            return res * res;
        }
    }

    @Test
    public void test() {
        Solution s = new Solution();
        char[][] nums = 
        {new char[]{'0','1','1','0','1'}
        ,new char[]{'1','1','0','1','0'},
        new char[]{'0','1','1','1','0'},
        new char[]{'1','1','1','1','0'},
        new char[]{'1','1','1','1','1'},
        new char[]{'0','0','0','0','0'}};
        System.out.println(s.maximalSquare(nums));
    }
}
